#include "chatwidget.h"
#include <QVBoxLayout>
#include <QHostAddress>
#include <QTcpServer>

ChatWidget::ChatWidget(const QString &role, QWidget *parent) : QWidget(parent), role(role) {
    // 初始化界面组件
    QVBoxLayout *layout = new QVBoxLayout(this);
    chatDisplay = new QTextEdit(this);
    chatDisplay->setReadOnly(true);  // 只读聊天记录

    inputField = new QLineEdit(this);
    sendButton = new QPushButton("Send", this);

    layout->addWidget(chatDisplay);
    layout->addWidget(inputField);
    layout->addWidget(sendButton);

    setLayout(layout);

    // 创建TCP套接字
    socket = new QTcpSocket(this);

    if (role == "doctor") {
        // 医生端作为客户端，连接到病人端
        socket->connectToHost("127.0.0.1", 12345);  // 假设病人端的IP和端口是127.0.0.1:12345

        // 检查连接状态
        connect(socket, &QTcpSocket::connected, this, [&]() {
            qDebug() << "Doctor connected to patient.";
        });

        connect(socket, &QTcpSocket::disconnected, this, [&]() {
            qDebug() << "Doctor disconnected from patient.";
        });

        connect(socket, &QTcpSocket::readyRead, this, [&]() {
            QByteArray data = socket->readAll();
            qDebug() << "Doctor received:" << data;
            chatDisplay->append("Patient: " + QString(data));
        });
    } else if (role == "patient") {
        // 病人端作为服务器，监听端口等待医生端连接
        QTcpServer *server = new QTcpServer(this);
        if (!server->listen(QHostAddress::Any, 12345)) {
            qDebug() << "Failed to start server!";
            return;
        }
        // 病人端监听新连接
        connect(server, &QTcpServer::newConnection, this, [=]() {
            socket = server->nextPendingConnection();
            connect(socket, &QTcpSocket::readyRead, this, &ChatWidget::on_readyRead);
            qDebug() << "Patient connected.";
        });
    }

    connect(sendButton, &QPushButton::clicked, this, &ChatWidget::onSendClicked);
}

void ChatWidget::onSendClicked() {
    QString message = inputField->text();
    sendMessage(message);
    inputField->clear();
}

void ChatWidget::sendMessage(const QString &message) {
    if (socket->state() == QTcpSocket::ConnectedState) {
        socket->write(message.toUtf8());
        socket->flush();  // 确保立即发送
        chatDisplay->append(role == "doctor" ? "Doctor: " : "Patient: " + message);
    } else {
        chatDisplay->append("Unable to send message. No connection.");
    }
}

void ChatWidget::on_readyRead() {
    QByteArray data = socket->readAll();
    qDebug() << "Received data:" << data;  // 打印接收到的数据
    chatDisplay->append(role == "doctor" ? "Patient: " + QString(data) : "Doctor: " + QString(data));
}
